<?php

class Order {
	
	/**
	 * 添加
	 *
	 */
	function add($order){

		//生成订单号
		$order_sn = '';

		$order_def = array(
			'order_sn'				=> '',
			'ip'					=> real_ip(),
			'created'				=> full_date()
		);
		
		$data = array_merge($order,$order_def);
		
		$mOrders = M('Orders');
		//返回自增id
		$id = $mOrders->add($data);

		return $id;
	}
	
	
	/**
	 * 添加
	 *
	 */
	function batch_add($order,$goods){
	
		//生成订单号
		$order_sn = $this->order_sn_generate();
	
		//会员的购物车
		import('@.ORG.Cart');
		$cCart = new Cart();
		 
		//购物车商品
		$goods = $cCart->lists();
		 
	
		//商品总金额
		$goods_amount = $cCart->goods_amount($goods);
		//快递费
		$shipping_fee = 0;
		//包装费
		$pack_fee 	= 0;
		//已支付金额
		$paid_amount = 0;
	
		$order_data = array(
				'user_id'				=> $user_id,
				'order_sn'				=> '',
				'order_status'			=> 0,
				'shipping_status'		=> 0,
				'pay_status'			=> 0,
				'goods_amount'			=> $goods_amount,
				'shipping_fee'			=> $shipping_fee,
				'paid_amount'			=> $paid_amount,
				'pack_fee'				=> $pack_fee,
				'ip'					=> real_ip(),
				'created'				=> full_date()
		);
	
		$data = $order_data + $order_detail;
	
		$mOrders = M('Orders');
		//返回自增id
		$id = $mOrders->add($data);
	
	
	
		if($id > 0){
			//写入订单商品表
			import('@.ORG.OrderGoods');
			$cOrderGoods = new OrderGoods();
	
			$order_goods = array();
	
			foreach($goods as $g){
				$order_goods[] = array(
						'order_id' 		=> $id,
						'goods_id' 		=> $g['goods_id'],
						'goods_number' 	=> $g['goods_number'],
						'goods_price' 	=> $g['goods_price'],
						'goods_attr' 	=> $g['goods_attr']
				);
			}
	
			$cOrderGoods->addAll($order_goods);
			//清空购物车
			$cCart->clear_by_user_id($user_id);
		}
	
		return $id;
	}
	
	
	
	/**
	 * 修改
	 *
	 * @param unknown_type $id
	 * @param unknown_type $upItems
	 * @return unknown
	 */
	function update($id,$upItems){
		$mOrders = M('Orders');
		return $mOrders -> where('order_id='.$id)->save($upItems);
	}
	
	function get_by_id($order_id){

		$mOrders = M('Orders');
		return $mOrders ->table('orders')
		->where('order_id = '.$order_id)
		->find();
	}
	
	function get_by_order_sn($order_sn){
		
		$order_amountSql = $this->order_amount_sql('o.');
		
		$mOrders = M('Orders');
		return $mOrders ->table('orders AS o')
		->join('users AS u ON u.id = o.user_id')
		->field('o.*,
			u.name AS user_name,
			u.real_name,
			u.mobile_phone AS user_mobile_phone,
			u.created AS user_created,
			'.$order_amountSql)
		->where("o.order_sn = '$order_sn'")
		->find();
	}

	function lists($where,$page,$pageSize,&$allCount){
		
		$where['end'] = short_date(strtotime($where['end']) + 86400);
		
		$whereSql = " AND (o.created BETWEEN '{$where['begin_time']}' AND '{$where['end_time']}') ";
		
		if($where['search'] != '' && $where['keywords'] != ''){
			$whereSql .= " AND o.{$where['search']} LIKE '%{$where['keywords']}%' ";
		}
		
		//全部状态
    	$all_status = C('ALL_STATUS');
    	
		//订单状态
		if($where['order_status'] != $all_status){
    		$whereSql .= " AND o.order_status = {$where['order_status']} ";
    	}
    	
    	if($where['pay_status'] != $all_status){
    		$whereSql .= " AND o.pay_status = {$where['pay_status']} ";
    	}
    	
    	if($where['shipping_status'] != $all_status){
    		$whereSql .= " AND o.shipping_status = {$where['shipping_status']} ";
    	}
		
		//开始行
		$startIndex = ($page-1) * $pageSize;
		
		//总计数
		$allCount = $this->lists_count($whereSql);
		
		//订单金额
		$order_amountSql = $this->order_amount_sql('o.');
		
		$mOrders = M('Orders');
		return $mOrders->table('orders o')
		->join('users AS u ON u.id = o.user_id')
		->order('o.order_id DESC')
		->where($whereSql)
		->limit($startIndex. ',' . $pageSize)
		->field('o.*,
			u.name AS user_name,'.$order_amountSql)
		->select();
	}
	
	function lists_count($whereSql){
		$mOrders = M('Orders');
		return $mOrders->table('orders o')->where($whereSql)->getField('COUNT(*)');
	}

	//生成订单
	function order_sn_generate(){
		/* 选择一个随机的方案 */
    	mt_srand((double) microtime() * 1000000);

    	return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
	}
	
	function get_by_user_id($user_id){
			
		//订单金额
		$order_amountSql = $this->order_amount_sql('orders.');
		
		$mOrders = M('Orders');
		return $mOrders->join('users AS u ON u.id = orders.user_id')
		->order('order_id DESC')
		->where('user_id = '.$user_id)
		->field('orders.*,
			u.name AS user_name,'.$order_amountSql)
		->select();
		
		
	}
	
	//订单金额
	function order_amount_sql($prefix = ''){
		return " ({$prefix}goods_amount + {$prefix}shipping_fee + {$prefix}pack_fee - {$prefix}bonus - {$prefix}discount) AS order_amount ";
	}
	
	//为订单附加数据
	function orders_append($orders){
	
		foreach ($orders as $i => $o){
			$orders[$i]['order_status_cn'] 		= self::order_status($o['order_status']);
			$orders[$i]['pay_status_cn'] 		= self::pay_status($o['pay_status']);
			$orders[$i]['shipping_status_cn'] 	= self::shipping_status($o['shipping_status']);
			$orders[$i]['postscript'] 			= replace_wrap($o['postscript']);
			$orders[$i]['created_short'] 		= substr($o['created'], 0,10);
		}
		return $orders;
	}
	
	//为订单附加数据
	function order_append($order){
	
		$order['order_status_cn'] 		= self::order_status($order['order_status']);
		$order['pay_status_cn'] 		= self::pay_status($order['pay_status']);
		$order['shipping_status_cn'] 	= self::shipping_status($order['shipping_status']);
		
		$order['should_pay'] 			= money($order['order_amount'] - $order['paid_amount']);
				
		return $order;
	}
	
	
	//订单状态
	static function order_status($id = null){
		
		static $status;
		if($status == null){
			$status = C('ORDER_STATUS');
		}
		
		if($id == null){
			return $status;
		}else{
			return $status[$id];
		}
	}
	
	//支付状态
	static function pay_status($id = null){
		
		static $status;
		if($status == null){
			$status = C('PAY_STATUS');
		}
		
	
		if($id == null){
			return $status;
		}else{
			return $status[$id];
		}
	}
	
	//发货状态
	static function shipping_status($id = null){
		static $status;
		if($status == null){
			$status = C('SHIPPING_STATUS');
		}
		
		if($id == null){
			return $status;
		}else{
			return $status[$id];
		}
	}
	
	function last_order($user_id){

		$order_amountSql = $this->order_amount_sql('o.');
		
		$mOrders = M('Orders');
		return $mOrders ->table('orders AS o')
		->join('users AS u ON u.id = o.user_id')
		->field('o.*,
			u.name AS user_name,
			u.real_name,
			u.mobile_phone AS user_mobile_phone,
			u.created AS user_created,
			'.$order_amountSql)
		->order('o.order_id DESC')
		->where('o.user_id = '.$user_id)
		->find();
	
	
	}
	

	/**
	 * 
	 * 更新订单商品总金额
	 * @param unknown_type $order_id
	 */
	function update_goods_amount($order_id){

		//订单商品总金额
		import('@.ORG.OrderGoods');
		
		$cOrderGoods = new OrderGoods();  	
		$goods_amount	= $cOrderGoods ->order_goods_amount($order_id);
		
		$upItems = array(
			'goods_amount' => $goods_amount
		);

		return $this->update($order_id,$upItems);		
	}
	
	/**
	 * 
	 * 任务单
	 * @param unknown_type $task_id
	 */
	function task_orders($task_id,$where=array(),$page = 1,$pageSize = PHP_INT_MAX, &$allCount){
		
		$whereSql = '';
		if(!empty($where)){
			if(isset($where['order_admin_id'])){
				$whereSql = ' AND o.order_admin_id = '.$where['order_admin_id'];
			}
		}
		
		$whereSql = "o.task_id = $task_id".$whereSql;
		
		//开始行
		$startIndex = ($page-1) * $pageSize;
		
		//总计数
		$allCount = $this->lists_count($whereSql);

		
		$mOrders = M('Orders');
		return $mOrders->table('orders o')
		->join('order_goods og ON og.order_id = o.order_id')
		->join('shipping s ON s.shipping_id = o.shipping_id')
		->join('admin a ON a.id = o.order_admin_id')
        ->join('member m ON m.member_id = o.member_id')
        ->join("status_type st ON st.status_id = o.receive_status AND st.type_code= 'receive_status'")
		->order('o.order_id ASC')
		->where($whereSql)
		->limit($startIndex. ',' . $pageSize)
		->field("
			o.*,
			
			og.goods_name,
			og.goods_url,
			og.goods_price,
			og.goods_number,
			og.final_price,
			og.search_rank,
			og.search_date,
			(o.paid_amount + o.bonus_money) AS real_price,
			
			s.shipping_name,
			a.real_name,
			m.member_name,
			m.member_pwd,
			m.member_pay_pwd,
			m.last_use_time,
			REPLACE(st.status_style,'#string',st.status_name) AS receive_status_name
		")
		->select();
	}

    /**
     * 区分不同颜色
     * @param $orders
     * @return mixed
     */
    function task_orders_set_background($orders){

        $last_goods_url = '';

        //开关
        $class = 0;

	    foreach($orders as $i => $o){

            $this_goods_url = $o['goods_url'];
            if($last_goods_url == ''){
                $last_goods_url = $this_goods_url;
            }

            if($last_goods_url == $this_goods_url){
                $change = 0;
            }else{
                $change = 1;
            }

            if($change){
                $class = ($class == 0) ? 1 : 0;
            }

            //最后颜色
            $last_goods_url = $this_goods_url;

            $orders[$i]['item_id'] = $this -> get_item_id($this_goods_url);
            $orders[$i]['class'] = $class;

            //排名可读化
            $orders[$i]['search_rank_fmt'] = rank_to_read($o['search_rank']);
        }
        return $orders;
	}


    /**
     * 获取商品id
     * @param $goods_url
     * @return mixed
     */
    function get_item_id($goods_url){

        preg_match('/\d+/',$goods_url,$match);

        if($match){
            return $match[0];
        }

        return $goods_url;
    }

	/**
	 * 
	 * 导出的订单
	 * @param unknown_type $task_id
	 */
	function export_orders($task_id){
	
		//订单
		$orders = $this->task_orders($task_id,$allCount = 0);
		
		//标题
		$header = explode(',', '订单号,快递公司,快递单号,收货人,收货地址,电话,产品链接,产品名称,关键词,购买量,刷单价,最终价,实际总金额,运费,评论');

		$data[] = $header;
	
		$sum_final_price 	= 0;
		$sum_real_price 	= 0;
		$sum_shipping_fee	= 0;
		

		foreach($orders as $i => $o){
			
			//最终价
			$sum_final_price += $o['final_price'];
			
			//实际总金额
			$real_price = $o['paid_amount'] + $o['bonus_money'];
			$sum_real_price += $real_price; 
			$sum_shipping_fee += $o['shipping_fee'];
			
			$data[] = array(
				$o['order_sn'],
				$o['shipping_name'],
				csv_number_wrap($o['invoice_no']),
				$o['consignee'],
				$o['address'],
				$o['mobile_phone'],
				$o['goods_url'],
				$o['goods_name'],
				$o['keywords'],
				$o['goods_number'],
				$o['goods_price'],
				$o['final_price'],
				$real_price,
				$o['shipping_fee'],
				$o['comment']
			);
		}
		
		$data[] = array(
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'',
			'总计:',
			$sum_final_price,
			$sum_real_price,
			$sum_shipping_fee
		);
		
		
		return $data;
	}
	
	
	/**
	 *
	 * 导出的订单,内容更多更详情
	 * @param unknown_type $task_id
	 */
	function export_orders_pro($task_id,$order_admin_id = 0){

        $where = array();
        if($order_admin_id > 0){
            $where['order_admin_id'] = $order_admin_id;
        }
		//订单
		$orders = $this->task_orders($task_id,$where);

		//标题
		$header = explode(',', '异常,帐号,登录密码,支付密码,下单URL,订单号,快递公司,快递单号,收货人,收货地址,电话,产品链接,产品名称,关键词,购买量,刷单价,最终价,实际总金额,用券金额,券后金额,运费,评论,备注');
	
		$data[] = $header;
	
		$sum_final_price 	= 0;
		$sum_real_price 	= 0;
		$sum_shipping_fee	= 0;
		$sum_goods_number	= 0;
		$sum_goods_price	= 0;
		$sum_bonus_money	= 0;
		$sum_paid_amount	= 0;

		foreach($orders as $i => $o){
				
			//最终价
			$sum_final_price += $o['final_price'];
			//总数量
			$sum_goods_number+= $o['goods_number'];
			//刷单价
			$sum_goods_price += $o['goods_price'];
			
			//实际总金额
			$real_price = $o['paid_amount'] + $o['bonus_money'];
			$sum_real_price += $real_price;
			$sum_shipping_fee += $o['shipping_fee'];
			
			//礼券
			$sum_bonus_money	+= $o['bonus_money'];
			//实际
			$sum_paid_amount	+= $o['paid_amount'];
			
			$is_exception = '否';
			if($o['is_exception']){
				$is_exception = '是';
			}
			
			$data[] = array(
					$is_exception,				//异常
					$o['member_name'],			//帐号
					$o['member_pwd'],			//登录密码
					$o['member_pay_pwd'],		//////支付密码
					$o['order_url'],			//下单URL
					csv_number_wrap($o['order_sn']),	//订单号
					$o['shipping_name'],		//快递公司
					csv_number_wrap($o['invoice_no']),			//快递单号
					$o['consignee'],			//收货人
					$o['address'],				//收货地址
					csv_number_wrap($o['mobile_phone']),			////电话
					$o['goods_url'],			//产品链接
					$o['goods_name'],			//产品名称
					$o['keywords'],				//关键词
					$o['goods_number'],			//购买量
					$o['goods_price'],			//刷单价
					$o['final_price'],			//最终价
					$real_price,				//实际总金额
					$o['bonus_money'],			//用券金额
					$o['paid_amount'],			//券后金额
					$o['shipping_fee'],			//运费
					$o['comment'],				//评论
					$o['remark']				//备注
			);
		}
	
		$data[] = array(
				'',
				'',
				'',
				'',
				'',
				'',
				'',
				'',
				'',
				'',
				'',
				'',
				'',
				'总计:',
				$sum_goods_number,
				$sum_goods_price,
				$sum_final_price,
				$sum_real_price,
				$sum_bonus_money,
				$sum_paid_amount,
				$sum_shipping_fee,
				'',
				''
		);
	
	
		return $data;
	}

    /**
     * 任务单汇总
     * @return mixed
     */
    function task_summary($task_id){

        $sql = <<<EOD
        SELECT
            o.order_admin_id,
            IFNULL(a.real_name,'未分配') AS admin_name,
            COUNT(o.order_id) AS order_count,
			SUM(o.paid_amount + o.bonus_money) AS order_money,
            SUM(o.paid_amount) AS paid_amount,
            SUM(o.bonus_money) AS bonus_money,
            SUM(IF(o.bonus_money > 0,1,0)) AS use_bonus_order,
            SUM(og.final_price) AS final_price
        FROM orders o
        LEFT JOIN order_goods og ON og.order_id = o.order_id       
        LEFT JOIN admin a ON a.id = o.order_admin_id
        WHERE o.task_id = $task_id
        GROUP BY o.order_admin_id
        ORDER BY order_count DESC
EOD;

        $mOrders = M('Orders');
        $summary = $mOrders->query($sql);

        return $summary;
    }
    
	//汇总金额
	function summary($summary){

        $order_count = 0;
		//实际总金额
		$order_money = 0;
		//券后金额
		$paid_amount = 0;
		//用券金额
		$bonus_money = 0;		
		//用券订单量
		$use_bonus_order = 0;
		//最终价
		$final_price	= 0;
		
		foreach($summary as $s){
            $order_count += $s['order_count'];
			$paid_amount += $s['paid_amount'];
			$bonus_money += $s['bonus_money'];
			$order_money += $s['order_money'];
            $use_bonus_order += $s['use_bonus_order'];
            $final_price	+= $s['final_price'];
		}
		
		return array(
			'order_count' => $order_count,
			//实际总金额
			'order_money' =>money($order_money),
			//券后金额
			'paid_amount' =>money($paid_amount),
			//用券金额
			'bonus_money' =>money($bonus_money),
			//用券订单量
			'use_bonus_order' =>$use_bonus_order,
			//最终价
			'final_price' =>money($final_price)
		);
	}
	
	//分配订单
	function assign_order($orders_id,$admin_id){

		$upItems = array(
			'order_admin_id' => $admin_id
		);
		
		$mOrders = M('Orders');
		return $mOrders -> where("order_id IN ($orders_id)")->save($upItems);
		
	}
	
	//订单分配会员
	function order_set_member($orders_id,$member_id){
		$upItems = array(
			'member_id' => $member_id
		);
		
		$mOrders = M('Orders');
		$order_up = $mOrders -> where("order_id = {$orders_id}")->save($upItems);
		
		//设置最后使用时间
		$cMember = new Member();
		$cMember->update($member_id, array(
			'last_use_time'	=> full_date()
		));

		return $order_up; 
	}
	
	//订单分配下单url
	function order_set_order_url($orders_id,$url){
		$upItems = array(
			'order_url' => $url['url']
		);
		
		$mOrders = M('Orders');
		$order_up = $mOrders -> where("order_id = {$orders_id}")->save($upItems);
		
		//设置最后使用时间
		$cKeywords = new Keywords();
		$cKeywords->update($url['id'], array(
			'last_use_time'	=> full_date()
		));

		return $order_up; 
	}
	
	//订单分配地址
	function order_set_address($orders_id,$addr){
		$upItems = array(
			'consignee' 	=> $addr['consignee'],
			'address' 		=> $addr['address'],
			'mobile_phone' 	=> $addr['mobile_phone']
		);
		
		$mOrders = M('Orders');
		$order_up = $mOrders -> where("order_id = {$orders_id}")->save($upItems);
		
		$id = $addr['id'];
		
		//设置最后使用时间
		$cUAddress = new UserAddress();
		$cUAddress->update($id, array(
			'last_use_time'	=> full_date()
		));

		return $order_up; 
	}

	/**
	 * 空地址订单
	 * @param unknown $task_id
	 * @return unknown
	 */
	function empty_address_order($task_id){
		
		//所有订单
		$orders  = $this->task_orders($task_id,$allCount = 0);
		
		foreach($orders as $i => $o){
			if(!empty($orders['consignee']) && !empty($orders['address']) && !empty($orders['mobile_phone'])){
				
				$orders[$i];
			}
		}
		
		return $orders;
	}
		

	/**
	 * 
	 * 最近几天下单会员 的id
	 * @param $user_id
	 * @param $days
	 */
    function recent_days_member_id(){
    	
    	
    	//内部帐户优先使用，内部是7天，外部是15天
    	$now_date = full_date();
    	$date_sql = " IFNULL(TIMESTAMPDIFF(DAY,last_use_time,'$now_date'),15) <= IF(is_internal=1,7,15) "; 
    	    	
    	$mMember = M('Member');
		
    	$members = $mMember ->table('member')
    	-> where($date_sql)
    	-> order('is_internal DESC') 
    	->getField('member_id',true);

    	return $members;
    }


    /**
     * 指定店铺的会员
     * 最近几天下单会员 的id
     * @param $user_id
     * @param $days
     */
    function recent_days_shop_member_id($user_id){

        //内部帐户优先使用，内部是7天，外部是15天
        $day_before = date('Y-m-d',strtotime('-7 days'));
        $date_sql = " t.user_id = $user_id AND o.member_id != 0 AND t.begin_time > '$day_before'";

        $mOrder = M('Orders');

        $members = $mOrder ->table('orders o')
            -> join('task t ON t.task_id = o.task_id')
            -> join('member m ON m.member_id = o.member_id')
            -> where($date_sql)
            -> order('m.is_internal DESC')
            -> field('DISTINCT(m.member_id) AS member_id')->select();

        $ret_member = array();
        foreach($members as $m){
            $ret_member[] = $m['member_id'];
        }

        return $ret_member;
    }

    /**
     * 
     * 重置会员
     * @param unknown_type $orders_id
     */
    function reset_member_id($orders_id){

        //会员id
        $mOrders = M('Orders');
        $member_ids = $mOrders -> where("order_id IN ($orders_id)")->getField('member_id',true);

        //禁用会员
        import('@.ORG.Member');
        $cMember = new Member();
        $cMember->disabled_member($member_ids);

        $upItems = array('member_id' => 0);
        $upReset = $mOrders -> where("order_id IN ($orders_id)")->save($upItems);

        return $upReset;
    }


    /**
     * 提交订单去收货确认
     * @param $orders_id
     * @return bool
     */
    function receive_submit_orders($orders_id){
        $upItems = array(
            'receive_status' => RECEIVE_SUBMIT,
            'receiving_time' => full_date()
        );

        //已收货
        $receive_received = RECEIVE_RECEIVED;

        $mOrders = M('Orders');
        return $mOrders -> where("order_id IN ($orders_id) AND receive_status != $receive_received")->save($upItems);
    }

    /**
     * 修改订单为未收货
     * @param $orders_id
     * @return bool
     */
    function receive_status_reset($orders_id){
        $upItems = array(
            'receive_status' => RECEIVE_UN_RECEIVE,
            'receiving_time' => null_date()
        );

        //已提交
        $receive_submit = RECEIVE_SUBMIT;
        //收货中
        $receive_receiveing = RECEIVE_RECEIVEING;
        //收货失败
        $receive_fail = RECEIVE_FAIL;

        $mOrders = M('Orders');
        return $mOrders -> where("order_id IN ($orders_id) AND receive_status IN ($receive_submit,$receive_receiveing,$receive_fail)")->save($upItems);
    }

	/**
	 * 同平台是否存在 快递号
	 * @param unknown $invoice_no
	 * @param unknown $task_id
	 */
    function invoice_no_exist($invoice_no,$task_id){
    	 
    	import('@.ORG.Task');
    	$this->cTask = new Task();
    	
    	//任务
    	$task 		= $this->cTask->get_by_task_id($task_id);
    	$user_id 	= $task['user_id']; 

    	import('@.ORG.Users');
    	$this->cUsers = new Users();
    	
    	//会员 
    	$user = $this->cUsers->get_by_user_id($user_id);
    	$plantform_id = $user['plantform_id'];
    	
    	$mOrders = M('Orders');
    	return $mOrders->table('orders o')
    	->join("INNER JOIN task AS t ON t.task_id = o.task_id")
    	->join("INNER JOIN users AS u ON u.user_id = t.user_id")
    	->where("u.plantform_id = $plantform_id AND o.invoice_no = '$invoice_no'")
    	->find();
    }

    /**
     * 一次获取未处理完的订单（分店铺获取）
     * @param $order_admin_id
     * @return array
     */
    function get_top_orders_by_admin_id($order_admin_id,$begin_time,$end_time){

        //一次只取3单
        $count = 10000;

        //1.未完成的任务单
        $task_ids = $this->get_unfinished_task_id($order_admin_id,$begin_time,$end_time);

        //2.获取任务列表
        $tasks = $this->get_task_by_ids($task_ids);


        //3.最后一条备注
        import('@.ORG.TaskLog');
        $cTaskLog = new TaskLog();

        $task_logs = $cTaskLog->get_last_task_log($task_ids);

        $task_logs = map_array($task_logs,'task_id');


        //以task_id为索引
        $tasks = map_array($tasks,'task_id');

        $task_orders    = array();
        $users          = array();

        foreach($task_ids as $task_id){
            //店铺会员id
            $user_id = $tasks[$task_id]['user_id'];

            if(!in_array($user_id,$users)){
                $users[] = $user_id;
                $task_orders[$task_id] = array(
                    'task'      => $tasks[$task_id],
                    'orders'    => $this->get_top_orders($order_admin_id,$task_id,$count),
                    'task_log'  => isset($task_logs[$task_id]) ? $task_logs[$task_id] : array()
                );
            }
        }

        return $task_orders;
    }



    /**
     * 获取刷单汇总，刷手的
     * @param $order_admin_id
     * @return array
     */
    function get_order_summary_by_admin_id($order_admin_id,$begin_time,$end_time){

        //执行中的，分配给刷手的
        $whereSql = "o.order_admin_id = $order_admin_id AND t.task_status != ".TS_CANCEL;

        $end_time = end_time_add($end_time);

        $whereSql .= " AND t.begin_time >= '$begin_time' AND t.end_time <= '$end_time'";

        $mOrders = M('Orders');
        $orders = $mOrders->table('orders o')
            ->join('task t ON t.task_id = o.task_id')
            ->where($whereSql)
            ->field("COUNT(o.order_id) AS order_count,IFNULL(SUM(o.is_finish),0) AS finish_count")->select();

        return $orders[0];
    }



    /**
     * 获取指定刷手未处理的任务单的前n个订单
     * @param $order_admin_id
     * @param $task_id
     * @param $count
     * @return mixed
     */
    private function get_top_orders($order_admin_id,$task_id,$count){

        $whereSql = "task_id = $task_id AND o.order_admin_id = $order_admin_id";

        $mOrders = M('Orders');
        $orders = $mOrders->table('orders o')
            ->join('order_goods og ON og.order_id = o.order_id')
            ->join('shipping s ON s.shipping_id = o.shipping_id')
            ->join('admin a ON a.id = o.order_admin_id')
            ->join('member m ON m.member_id = o.member_id')
            ->join("status_type st ON st.status_id = o.receive_status AND st.type_code= 'receive_status'")
            ->order('o.order_id ASC')
            ->where($whereSql)
            ->limit('0,' . $count)
            ->field("
			o.*,
			og.goods_name,
			og.goods_url,
			og.goods_price,
			og.goods_number,
			og.final_price,
			og.search_rank,
			og.search_date,
			(o.paid_amount + o.bonus_money) AS real_price,

			s.shipping_name,
			a.real_name,
			m.member_name,
			m.member_pwd,
			m.member_pay_pwd,
			m.last_use_time,
			REPLACE(st.status_style,'#string',st.status_name) AS receive_status_name
		")
            ->select();


        return $this->task_orders_set_background($orders);

    }


    /**
     * 获取指定任务单完整信息
     * @param $task_ids
     * @return mixed
     */
    function get_task_by_ids($task_ids){

        $ids = '0';
        if(!empty($task_ids)){
            $ids = implode(',',$task_ids);
        }

        $m = M('Task');

        return $m->table('task t')
            ->join('users u ON u.user_id = t.user_id')
            ->join('plantform p ON p.plantform_id = u.plantform_id')
            ->where("t.task_id IN ($ids)")
            ->order('t.end_time ASC')
            ->field('t.*,u.plantform_id,u.shop_name,u.shop_url,p.plantform_name')
            ->select();
    }
    /**
     * 获取未完成的任务id号
     * @param int $order_admin_id
     * @return mixed
     */
    function get_unfinished_task_id($order_admin_id = 0,$begin_time,$end_time){

        $whereSql = " o.is_finish = 0 AND t.task_status != -1";
        if($order_admin_id > 0){
            $whereSql .= ' AND order_admin_id = '.$order_admin_id;
        }

        $end_time = end_time_add($end_time);

        $whereSql .= " AND t.begin_time >= '$begin_time' AND t.end_time <= '$end_time'";

        $mOrders = M('Orders');
        $orders = $mOrders->table('orders o')
            ->join("INNER JOIN task AS t ON t.task_id = o.task_id")
            ->where($whereSql)
            ->group('o.task_id')
            ->field('DISTINCT(o.task_id) AS task_id')->select();

        $task_ids = array();
        if(!empty($orders)){
            foreach($orders  as $o){
                $task_ids[] = $o['task_id'];
            }
        }

        return $task_ids;
    }

    /**
     * 收货确认记录
     * @param $begin_time
     * @param $end_time
     * @return mixed
     */
    function order_received_log($begin_time,$end_time,$page,$pageSize,&$allCount){

        $end_time = end_time_add($end_time);

        $whereSql = "o.received_time between '$begin_time' and '$end_time' and o.receive_status=".RECEIVE_RECEIVED;
        $mOrders = M('Orders');

        //总计数
        $allCount = $this->order_received_log_count($whereSql);

        //开始行
        $startIndex = ($page - 1) * $pageSize;


        return $mOrders->table('orders o')
            ->join("INNER JOIN task AS t ON t.task_id = o.task_id")
            ->join("INNER JOIN users u on u.user_id = t.user_id")
            ->join("INNER JOIN order_goods AS og ON og.order_id = o.order_id")
            ->where($whereSql)
            ->field('u.shop_name,
                    o.order_sn,
                    IFNULL(o.ordered_time,t.begin_time) AS ordered_time,
                    o.received_time,
                    DATEDIFF(o.received_time,IFNULL(o.ordered_time,t.begin_time)) AS day_span,
                    o.proxy_ip,
                    og.goods_id,
                    og.goods_name,
                    og.goods_url
                    ')
            ->order('o.received_time DESC')
            ->limit($startIndex. ',' . $pageSize)
            ->select();

    }


    /**
     * 收货确认记录
     * @param $begin_time
     * @param $end_time
     * @return mixed
     */
    function order_commented_log($begin_time,$end_time,$page,$pageSize,&$allCount){

        $end_time = end_time_add($end_time);

        $whereSql = "o.commented_time between '$begin_time' and '$end_time' and o.comment_status=".COMMENT_RECEIVED;
        $mOrders = M('Orders');

        //总计数
        $allCount = $this->order_commented_log_count($whereSql);

        //开始行
        $startIndex = ($page - 1) * $pageSize;


        return $mOrders->table('orders o')
            ->join("INNER JOIN task AS t ON t.task_id = o.task_id")
            ->join("INNER JOIN users u on u.user_id = t.user_id")
            ->join("INNER JOIN order_goods AS og ON og.order_id = o.order_id")
            ->where($whereSql)
            ->field('u.shop_name,
                    o.order_sn,
                    IFNULL(o.ordered_time,t.begin_time) AS ordered_time,
                    o.commented_time,
                    DATEDIFF(o.commented_time,IFNULL(o.ordered_time,t.begin_time)) AS day_span,
                    og.goods_id,
                    o.comment,
                    og.goods_name,
                    og.goods_url
                    ')
            ->order('o.commented_time DESC')
            ->limit($startIndex. ',' . $pageSize)
            ->select();

    }



    function order_commented_log_count($whereSql){

        $mOrders = M('Orders');

        return $mOrders->table('orders o')
            ->join("INNER JOIN task AS t ON t.task_id = o.task_id")
            ->join("INNER JOIN users u on u.user_id = t.user_id")
            ->where($whereSql)
            ->getField('COUNT(*)');

    }



    /**
     * 最离现在时间最早的提交的待确认的订单
     * @return array
     */
    function get_receive_submit_order_count(){

        $mOrders = M('Orders');

        return $mOrders->where('receive_status = '.RECEIVE_SUBMIT)
            ->getField('COUNT(*)');
    }


    /**
     * 最离现在时间最早的提交的待确认的订单
     * @return array
     */
    function get_comment_submit_order_count(){

        $mOrders = M('Orders');

        return $mOrders->where('comment_status = '.COMMENT_SUBMIT)
            ->getField('COUNT(*)');
    }



    /**
     * 正在收货中的商品id
     * @return array
     */
    function get_one_receiving_goods(){


        //完毕
        $ts_finish = TS_FINISH;
        //收货中
        $receive_receiveing = RECEIVE_RECEIVEING;


        $mOrders = M('Orders');

        $goods = $mOrders->alias('o')
            ->join('LEFT JOIN member m ON m.member_id = o.member_id')
            ->join('LEFT JOIN task t ON t.task_id = o.task_id AND t.task_status = '.$ts_finish)
            ->join('LEFT JOIN order_goods og ON og.order_id = o.order_id')
            ->where('o.receive_status = '.$receive_receiveing)
            ->field('og.goods_id')
            ->select();

        $goods_id = get_array_cols($goods,'goods_id','array');

        return $goods_id;
    }


    /**
     * 正在收货中的商品id
     * @return array
     */
    function get_one_commenting_goods(){


        //完毕
        $ts_finish = TS_FINISH;
        //收货中
        $comment_receiveing = COMMENT_RECEIVEING;


        $mOrders = M('Orders');

        $goods = $mOrders->alias('o')
            ->join('LEFT JOIN member m ON m.member_id = o.member_id')
            ->join('LEFT JOIN task t ON t.task_id = o.task_id AND t.task_status = '.$ts_finish)
            ->join('LEFT JOIN order_goods og ON og.order_id = o.order_id')
            ->where('o.comment_status = '.$comment_receiveing)
            ->field('og.goods_id')
            ->select();

        $goods_id = get_array_cols($goods,'goods_id','array');

        return $goods_id;
    }

}